﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.UI;
using System.Data.Linq;
using Basmus.DataStructures.Generic;
using System.Collections.Specialized;

namespace Basmus.BindingFramework
{
	public class PageDataContextBinder
	{
		public AttributiveNamedTuples namedTuples { get; private set; }

		public LinqToSqlClasses linqToSqlClasses { get; private set; }

		private Page targetPage;

		public PageDataContextBinder(Page page, DataContext dataContext)
		{
			targetPage = page;
			namedTuples = new AttributiveNamedTuples(page.GetType());
			linqToSqlClasses = new LinqToSqlClasses(dataContext);
		}
		public void ApplyRules(IEnumerable<Pair<string, string>> rules)
		{
			foreach (var rule in rules)
			{
				var elementType = namedTuples.ElementType(rule.First);
				var tuple = linqToSqlClasses.Tuple(elementType, rule.Second);
				namedTuples.SetTuple(targetPage, rule.First, tuple);
			}
		}
		public IEnumerable<Pair<string, string>> GetRules()
		{
			foreach (var name in namedTuples.Names)
			{
				var tuple = namedTuples.GetTuple(targetPage, name);
				var identity = linqToSqlClasses.Identity(tuple);
				var rule = new Pair<string, string> { First = name, Second = identity };
				yield return rule;
			}
		}
		public void ApplyNameValueCollectionRules(NameValueCollection nameValueCollection)
		{
			var rules = nameValueCollection.ToComponentSystemSheme();
			ApplyRules(rules);
		}
		public NameValueCollection GetNameValueCollectionRules()
		{
			var rules = GetRules();
			return rules.ToNameValueCollection();
		}
	}
}
